package com.gientech.redisdemo.Controller;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@RestController
public class RedisController {

    @Resource
    StringRedisTemplate stringRedisTemplate;


    @GetMapping("redis/setvalue")
    public String setValue(){
        String key = "myconfig";
        String value = "this is my config";

        stringRedisTemplate.opsForValue().set(key,value);

        return "set "+ key +" succ, value is " + value;
    }

    @GetMapping("redis/getvalue")
    public String getValue(){
        String key = "myconfig";

        String str = stringRedisTemplate.opsForValue().get(key);
        if( str == null ){
//            requset database
        }
        return str;
    }

    @GetMapping("redis/setlock")
    public String setLock(){
        String key = "lockmyconfig";
        String value = "1";
        int lockTime = 20;

        stringRedisTemplate.opsForValue().set(key,value,lockTime,TimeUnit.SECONDS);

        return "set "+ key +"-" + value + ",lock " + lockTime + "s";
    }

    @GetMapping("redis/dellock")
    public String delLock(){
        String key = "lockmyconfig";
        String str = stringRedisTemplate.opsForValue().getAndDelete(key);
        if( str == null ){
//            requset database
        }
        return key +"-" + str + "is unlock";
    }
}
